package lib.quasar.db.manager;

import android.content.Context;
import android.content.ContextWrapper;
import android.database.DatabaseErrorHandler;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

import lib.quasar.db.R;

/**
 * description: 数据库路径
 * created by kalu on 2018/4/16 20:47
 */
public class DBContextWrapper extends ContextWrapper {

    public DBContextWrapper(Context base) {
        super(base);
    }

    @Override
    public File getDatabasePath(String dbName) {
        String filePath = getApplicationContext().getDatabasePath(dbName).getAbsolutePath();
        File file = new File(filePath);
        if (!file.exists()) {
            createDatabase(filePath);
        }
        return file;
    }

    /**
     * 创建数据库文件，其实就是将raw文件夹下的数据库文件复制到应用的database文件夹下：
     * /data/data/com.xxxx/databases/
     */
    private void createDatabase(String filePath) {
        InputStream inputStream = getApplicationContext().getResources().openRawResource(R.raw.quasar_patient);
        FileOutputStream fos;
        try {
            fos = new FileOutputStream(filePath);
            byte[] buffer = new byte[1024];
            int length;
            while ((length = inputStream.read(buffer)) > 0) {
                fos.write(buffer, 0, length);
            }
            fos.close();
            inputStream.close();
        } catch (Exception e) {
            Log.e("", e.getMessage(), e);
        }
    }

    /**
     * 重载这个方法，是用来打开SD卡上的数据库的，android 2.3及以下会调用这个方法。
     */
    @Override
    public SQLiteDatabase openOrCreateDatabase(String name, int mode, SQLiteDatabase.CursorFactory factory) {
        SQLiteDatabase result = SQLiteDatabase.openOrCreateDatabase(getDatabasePath(name), factory);
        return result;
    }

    /**
     * Android 4.0会调用此方法获取数据库。
     */
    @Override
    public SQLiteDatabase openOrCreateDatabase(String name, int mode, SQLiteDatabase.CursorFactory factory, DatabaseErrorHandler errorHandler) {
        SQLiteDatabase result = SQLiteDatabase.openOrCreateDatabase(getDatabasePath(name), factory);
        return result;
    }
}